/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.hutech09.jsale.web.manager.product.info;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.hutech09.jsale.bsn.IProductManager;
import org.hutech09.jsale.bsn.exception.ItemNotFoundException;
import org.hutech09.jsale.entity.Product;
import org.hutech09.jsale.entity.ProductDetail;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Nam
 */
@ManagedBean
@SessionScoped
public class PropertyCtrl {

    @EJB
    private IProductManager pm;

    private Product product;

    private List<PropertyRow> properties;

    private PropertyRow selected;

    public void getAllProperties() {
        List<PropertyRow> rows = new ArrayList<PropertyRow>();
        if (product != null) {
            try {
                PropertyRow row;
                for (ProductDetail detail : pm.getDetail(product.getId())) {
                    row = new PropertyRow(detail.getInfoType().getName(), detail, detail.getVal());
                    rows.add(row);
                }
            } catch (ItemNotFoundException ex) {
                Logger.getLogger(PropertyCtrl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        this.properties = rows;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public List<PropertyRow> getProperties() {
        return properties;
    }

    public void setProperties(List<PropertyRow> properties) {
        this.properties = properties;
    }

    public void showProperties(Product p) {
        this.product = p;
        getAllProperties();
    }

    public void onEdit(RowEditEvent event) {
        PropertyRow detail = (PropertyRow) event.getObject();
        detail.getDetail().setValue(detail.getValue());
        try {
            pm.updateProductDetail(detail.getDetail());
        } catch (ItemNotFoundException ex) {
            Logger.getLogger(PropertyCtrl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void delete() {
        System.err.println(selected.getDetail());
        if (selected != null) {
            try {
                pm.deleteProductDetail(selected.getDetail());
                getAllProperties();
            } catch (ItemNotFoundException ex) {
                Logger.getLogger(PropertyCtrl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public PropertyRow getSelected() {
        return selected;
    }

    public void setSelected(PropertyRow selected) {
        this.selected = selected;
    }
}
